package bootstrap

import (
	"errors"
	"gitee.com/guolianyu/kit/skit/third_party/config"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/exporters/jaeger"
	"go.opentelemetry.io/otel/sdk/resource"
	"go.opentelemetry.io/otel/sdk/trace"
	semConv "go.opentelemetry.io/otel/semconv/v1.4.0"
)

// NewTracerProvider 链路追踪
func NewTracerProvider(cfg *config.Trace, serviceInfo *ServiceInfo) error {
	if cfg == nil {
		return errors.New("tracer config can not be nil")
	}
	//jaeger
	exp, err := jaeger.New(jaeger.WithCollectorEndpoint(jaeger.WithEndpoint(cfg.GetEndpoint())))
	if err != nil {
		return err
	}
	tp := trace.NewTracerProvider(
		trace.WithSampler(trace.ParentBased(trace.TraceIDRatioBased(1.0))),
		trace.WithBatcher(exp),
		trace.WithResource(resource.NewSchemaless(
			semConv.ServiceNameKey.String(serviceInfo.Name),
			semConv.ServiceVersionKey.String(serviceInfo.Version),
			semConv.ServiceInstanceIDKey.String(serviceInfo.Id),
			attribute.String("env", cfg.Env),
		)),
	)
	otel.SetTracerProvider(tp)
	return nil
}
